<?php
namespace App\Http\Controllers\CRM;
use App\Order;
use App\Rad_user;
use App\Rad_user_account;
use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;
use App\Radgroupreply;
use App\Rad_users;
use App\Rad_account;
use App\Rad_merge_data;
use DB;
use App\Rad_manage_discount;
use App\Rad_order;
use App\Line;
use App\Agent;
use App\Teamqq;

use App\Manage_user_list;
use App\Discount;
use App\Http\Controllers\Controller;
use Redis;
use App\Terrace;
use App\Http\Controllers\CRM\PublicController;

class AddUserController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

    }


    /**
     * @param \App\Http\Controllers\CRM\Request $request
     * @param 添加父用户
     * @param  username
     * @param  QQ
     * @param  password
     * @param  mobile
     */
    public function AddUser(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        //  名称
        if(!$request->has('username') && empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $username = trim($request->input('username'));


        if (strlen($username) > 20){
            self::ShowError(ErrorDefine::INVALID_USERNAME);
            return;
        }



        $user = Rad_users::where('username',$username)->first();

        if($user != NULL){
            self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
            return;
        }


        //  名称
        if(!$request->has('mobile') && empty($request->input('mobile')) )
        {
            self::ShowError(ErrorDefine::PHONE_NOT_EXIST);
            return;
        }

        $mobile = trim($request->input('mobile'));


        if (preg_match("/[\x7f-\xff]/", $mobile))
        {
            self::ShowError(ErrorDefine::PHONE_NOT_EXIST);
            return;
        }

        if (strlen($mobile) !=11 ){
            self::ShowError(ErrorDefine::PHONE_NOT_EXIST);
            return;
        }

        $user = Rad_users::where('mobile',$mobile)->first();
        if($user != NULL){
            self::ShowError(ErrorDefine::PHONE_IS_EXIST);
            return;
        }


        if(!$request->has('qq') && empty($request->input('qq')) )
        {
            self::ShowError(ErrorDefine::INVALID_QQ);
            return;
        }
        $qq = trim($request->input('qq'));

        if (preg_match("/[\x7f-\xff]/", $qq))
        {
            self::ShowError(ErrorDefine::INVALID_QQ);
            return;
        }

        //   用户token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        $public = new PublicController();

        //   获取用户ID
        $users = $public->getTokenById($token);

        if(empty($users))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        //    备注
        $remark = '';
        if($request->input('remark'))
        {
            $remark = trim($request->input('remark'));
        }
        $manage_id =  $users[0]['manage_id'];
        $account_type = '';
        $expired_at = '';
        $where = [];
        $where['manage_id'] = $manage_id;
        $where['con_max'] = 0;
        $where['account_type'] = '手动添加';
        $where['vip'] = 0;
        $where['qq'] =$qq;
        $where['username'] =$username;
        $where['mobile'] =$mobile;
        $where['account_num'] =0;
        $where['total_consumption'] =0;

        $id = Rad_users::insertGetId($where);

        if($id)
        {

            $users = Rad_users::find($id);
            $users->pid = $id;
            $users->save();
            return self::ShowMessage();
        }else{
            self::ShowError(ErrorDefine::DATABASE_ERROR);
            return;
        }

    }




    public function AddChildAccount(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') || empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $username = trim($request->input('username'));


        //  密码
        if(!$request->has('password') || empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }

        $password =  trim($request->input('password'));


        //  账号类型
        if(!$request->has('account_type') || empty($request->input('account_type')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_TYPE_ONT_EXIST);
            return;
        }
        $account_type = $request->input('account_type');


        //  连接数
        if(!$request->has('concent_num') || empty($request->input('concent_num')) )
        {
            self::ShowError(ErrorDefine::CONCENT_NOT_EXIST);
            return;
        }
        $connect_num = $request->input('concent_num');

        //   检测连接数
        if($connect_num <=0 )
        {
            self::ShowError(ErrorDefine::ILLEGAL_CONNECT_NUM);
            return;
        }


        //   用户token
        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //    备注
        $remark = '';
        if($request->input('remark'))
        {
            $remark = trim($request->input('remark'));
        }

        //  订单号
        if(!$request->has('order_id') || empty($request->input('order_id')))
        {
            self::ShowError(ErrorDefine::ORDER_NO_NOT_EXIST);
            return;
        }
        $order_no = $request->input('order_id');

        $money = 0;
        if($account_type != '测试')
        {

            //   日期卡类型
            if(!$request->has('date_type') || empty($request->input('date_type')))
            {
                self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
                return;
            }
            $date_type = $request->input('date_type');



            //     开通时间
            if(!$request->has('date') || empty($request->input('date')))
            {
                self::ShowError(ErrorDefine::DATE_NOT_EXIST);
                return;
            }

            $date = $request->input('date');


            if($date<=0) {
                self::ShowError(ErrorDefine::INVALID_DATE);
                return;
            }

            if(!$request->has('money') || empty($request->input('money')))
            {
                self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
                return;
            }
            $money = $request->input('money');

        }


//           用户类型   1   是普通用户  暂时默认普通
        if(!$request->has('set-meal-type') && empty($request->input('set-meal-type')))
        {
            self::ShowError(ErrorDefine::USER_TYPE_NO_EXIST);
            return;
        }
        $set_meal_type = $request->input('set-meal-type');
        $public = new PublicController();

        //   获取用户ID
        $users = $public->getTokenById($token);

        if(empty($users))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $manage_id =  $users[0]['manage_id'];

dd($money);
        //   判断   余额是否支持开户
        if($account_type !='测试')
        {
            if( $users[0]['balance'] < $money)
            {
                return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
            }
        }



        //   检测用户名是否存在
        $user = Radcheck::where('username',$username)->get(['id','username'])->toArray();
        if(!empty($user))
        {
            self::ShowError(ErrorDefine::USER_IS_EXIST);
            return;
        }


        // 开户时间  测试一小时
        if($account_type !='测试') {
            switch ($date_type) {
                case '日':
                    $expired_at = time() + 86400 * $date * 1;
                    break;
                case '周':
                    $expired_at = time() + 86400 * $date * 7;
                    break;
                case '月':
                    $expired_at = time() + 86400 * $date * 30;
                    break;
                default : self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);return;break;
            }
        }else{
            $expired_at = time()+3600;
        }

        //   到期时间
        $time = date("d M Y H:i:s ",$expired_at);

        switch($set_meal_type)
        {
            case 1: $speed = '512k/512k';break;
            case 2: $speed = '2048k/2048k';break;
            case 3: $speed = '4096k/4096k';break;
            default: self::ShowError(ErrorDefine::USER_TYPE_NO_EXIST);return;break;
        }


        $public = new PublicController();
        $public->checkRadiusUserGroup($connect_num);

        $account_id = $public->AddRadcheck($username,$password,$time,$speed,$connect_num);


        //   用户账号表
        $account = [];
        $account['manage_id'] = $manage_id;
        $account['pid'] = $pid;
        $account['user_id'] = $account_id;
        $account['username'] = $username;
        $account['password'] = $password;
        $account['terrace_id'] = 0;
        $account['con_max'] =$connect_num ;
        $account['created_at'] = date('Y-m-d H:i:s',time());
        $account['updated_at'] = date('Y-m-d H:i:s',time());
        $account['expired_at'] = date('Y-m-d H:i:s',$expired_at);
        $account['account_type'] = $account_type;
        $account['vip'] = 1;
        $account['balance'] = $money;
        $account['remark'] = $remark;
        $account['set_meal_type'] = $set_meal_type;     //  套餐类型  1：基础  2：初级  3：高级
        $ret = Rad_users::insertGetId($account);


        //   订单信息
        $oder = [];
        if($account_type !='测试')
        {
            $order['balance'] = $users[0]['balance']-$money;
            $order['date'] = $date;
            $order['price'] = $money;
        }else{
            $order['balance'] = $users[0]['balance'];
            $order['date'] = 0;
            $order['price'] =0;
        }

        $order['account_type'] = $account_type;
        $order['connect_num'] =$connect_num;
        $order['status'] =1;
        $order['user_id'] = $manage_id;                 //   用户id
        $order['to_user'] =$account_id;
        $order['order_no'] =$order_no;
        $order['pay_channel'] =2;                    //    支付标识   余额  2
        $order['created_at'] = date('Y-m-d H:i:s',time());
        $order['updated_at'] = date('Y-m-d H:i:s',time());

        $id = Rad_order::insertGetId($order);

        if($account_type !='测试')
        {
            $user = Rad_manage::find($manage_id);
            $user->balance = $user->balance - $money;
            $user->save();

            $parent->total_consumption = $parent->total_consumption + $money;

        }



        $parent->account_num = $parent->account_num + 1;
        $parent->save();

        return self::ShowMessage();

    }


    /**
     * @param Request $request
     * 批量添加子账号
     */
    public function batchAddChildAccount(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        //  父级信息
        if(!$request->has('pid') && empty($request->input('pid')))
        {
            self::ShowError(ErrorDefine::INVALID_PID);
            return;
        }
        $pid = $request->input('pid');

        $parent = Rad_users::find($pid);
        if($parent == NUll)
        {
            self::ShowError(ErrorDefine::INVALID_PID);
            return;
        }

        //  批量添加用户名
        if(!$request->has('batch-add-username') || empty($request->has('batch-add-username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = explode(',',$request->input('batch-add-username'));

        if(!$request->has('set-meal-type') || empty($request->has('set-meal-type')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $set_meal_type = $request->input('set-meal-type');

        //  检测用户是否在
        $_user  = Rad_users::whereIn('username',$username)->get()->toArray();

        $_check = Radcheck::whereIn('username',$username)->get()->toArray();


        if(!empty($_user) && !empty($_check))
        {
            self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
            return;
        }


        //   批量添加密码
        if(!$request->has('batch-password') && empty($request->input('batch-password')))
        {
            self::ShowError(ErrorDefine::ILLEGAL_PASSWORD);
            return;
        }
        $password = $request->input('batch-password');

        //  批量添加日期类型
        if(!$request->has('batch-add-date-type') && empty($request->input('batch-add-date-type')))
        {
            self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
            return;
        }
        $date_type = $request->input('batch-add-date-type');


        //   批量开通连接数
        if(!$request->has('batch-connect-num') && empty($request->input('batch-connect-num')) )
        {
            self::ShowError(ErrorDefine::CONCENT_NOT_EXIST);
            return;
        }
        $connect_num = $request->input('batch-connect-num');

        if($connect_num <=0 )
        {
            self::ShowError(ErrorDefine::ILLEGAL_CONNECT_NUM);
            return;
        }

        //   开户人的 token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        //  批量添加的日期
        if(!$request->has('batch-add-date') && empty($request->input('batch-add-date')))
        {
            self::ShowError(ErrorDefine::DATE_NOT_EXIST);
            return;
        }
        $add_date= $request->input('batch-add-date');

        if($add_date<=0) {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }


        //   开通账号数量
        if(!$request->has('batch-add-num') && empty($request->input('batch-add-num')) )
        {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }
        $batch_add_num = $request->input('batch-add-num');


        // 批量添加的价格
        if(!$request->has('batch-add-price') && empty($request->input('batch-add-price')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $price = $request->input('batch-add-price');

        $public  = new PublicController();

        $user = $public->getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $manage_id =  $user[0]['manage_id'];

        if( $user[0]['balance'] < $price)
        {
            return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
        }

        switch ($date_type) {
            case '日':
                $expired_at = time() + 86400 * $add_date * 1;
                break;
            case '周':
                $expired_at = time() + 86400 * $add_date * 7;
                break;
            case '月':
                $expired_at = time() + 86400 * $add_date * 30;
                break;
            default:  self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);return;break;
        }

        //  radcheck 到期时间
        $radcheck_at = date("d M Y H:i:s ",$expired_at);

        $money = $price / $batch_add_num;


        switch($set_meal_type)
        {
            case 1: $speed= '512k/512k';break;
            case 2:  $speed = '2048k/2048k';break;
            case 3: $speed = '4096k/4096k';break;
            default: self::ShowError(ErrorDefine::USER_TYPE_NO_EXIST);return;break;
        }

        $num = count($username);
        foreach($username as $value)
        {


            $account_id = $public->AddRadcheck($value,$password,$radcheck_at,$speed,$connect_num);

            //  添加用户数据
            $account = [];

            $account['manage_id'] = $manage_id;
            $account['user_id'] = $account_id;
            $account['username'] = $value;
            $account['password'] = $password;
            $account['terrace_id'] = 0;             //  平台标识  5 代理平台
            $account['con_max'] =$connect_num ;
            $account['created_at'] = date('Y-m-d H:i:s',time());
            $account['updated_at'] = date('Y-m-d H:i:s',time());
            $account['expired_at'] = date('Y-m-d H:i:s',$expired_at);
            $account['account_type'] = '付费';
            $account['vip'] = 1;
            $account['set_meal_type'] = $set_meal_type;
            $account['pid'] = $pid;

            $ret = Rad_users::insertGetId($account);

            $public->checkRadiusUserGroup($connect_num);

        }

        $rad = Rad_manage::find($manage_id);
        //  订单
        $order = [];
        $order['order_no'] = $public->createUuid();
        $order['user_id'] =$manage_id ;
        $order['pay_channel'] =2;
        $order['account_type'] = '付费';
        $order['date'] =$add_date;
        $order['price'] =$price;
        $order['balance'] =$rad->balance - $price;
        $order['created_at'] = date('Y-m-d H:i:s',time());
        $order['updated_at'] = date('Y-m-d H:i:s',time());
        $order['status'] = 1;
        $id = Rad_order::insertGetId($order);

        $rad->balance = $rad->balance-$money;
        $rad->save();

        $parent->total_consumption = $parent->total_consumption + $price;
        $parent->account_num = $parent->account_num + $num;
        $parent->save();
        return self::ShowMessage();

    }



}